//
//  NSObject+KVO.m
//  利用runtime创建KVO
//
//  Created by 马文星 on 16/6/13.
//  Copyright © 2016年 Demos. All rights reserved.
//

#import "NSObject+KVO.h"
#import "Person_KVO.h"
#import <objc/runtime.h>


@implementation NSObject (KVO)


- (void)ml_addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context{

    //修改isa指针，就是把`当前对象`指向一个`新类`
    // Person's isa ->  Person_KVO
    // Class object_setClass(id obj, Class cls)
    //使当前对象的isa指向新的派生类(Person_KVO)，就会调用派生类的set方法
    object_setClass(self, [Person_KVO class]);
    
    //给对象绑定观察者对象
    objc_setAssociatedObject(self, @"observer", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
